<?php

namespace plugin\voice\app\controller;

use Webman\Medoo\Medoo as db;
use support\Request;
use support\Response;

class IndexController
{

    public function index()
    {
        
        return view('index/index', ['name' => 'voice']);
    }
    
    public function voice(Request $request){
        $setting          = db::get('voice_settings','*');
        $text             = $request->post('content');
        $voice            = $request->post('voice');
        $openai_api_key   = $setting['gpt_api_key'];
        $model            = "tts-1";
        $url              = $setting['gpt_api_host']."/v1/audio/speech";
        $headers          = [
            "Authorization: Bearer $openai_api_key",
            "Content-Type: application/json"
        ];
        $data = json_encode([
            "model"       => $model,
            "input"       => $text,
            "voice"       => $voice
        ]);
        $options = [
            'http' => [
                'header'  => $headers,
                'method'  => 'POST',
                'content' => $data
            ]
        ];
        $context    = stream_context_create($options);
        $result     = file_get_contents($url, false, $context);
        if ($result === FALSE) {
            return json([
                'code' => -1,
                'msg'  =>"Error: " . http_response_code()
            ]);
        }
        $fileName   = date('YmdHis').mt_rand(1000,9999).'.mp3';
        $filePath   = dirname(dirname(dirname(__FILE__))).'/public/user/chat/'.$fileName;
        file_put_contents($filePath, $result);
        return json([
            'code'  => 200,
            'msg'   => 'ok',
            'data'  => '/app/voice/user/chat/'.$fileName
        ]);
    }
    
}
